// pages/accounting_voucher_detl/accounting_voucher_detl.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    urlParams: {},

    vchrId: '',
    edit: false,

    voucherId: '',
    date: '',
    abstractStr: '',
    list: [],
    borrow: 0,
    loan: 0,
    inputName: '',

    subjectObj: {},

  },

  navTo(e) {
    './pages/accounting/edit_voucher.html?type=edit&table_id=all_voucher&period=202208&voucher_id=记2022080025'
    let { voucherId, date, urlParams, } = this.data,
        arr = date.split('-'),
        period = `${arr[0]}${arr[1]}`,
        paramsArr = [ 'type=edit', ],
        url = '../accounting_voucher_add/accounting_voucher_add?'
    Object.entries(urlParams).forEach((arr) => {
      if(arr[0] !== 'canedit') paramsArr.push(arr.join('='))
    })
    url += `${paramsArr.join('&')}`
    wx.navigateTo({
      url,
    })
  },

  // 接口
  ready() {
    let p0 = this.getSubjectList(),
        p1 = this.getAssistProject()

    return new Promise((resolve, reject) => {
      Promise.all([p0, p1]).then(res => {
        let rows = res[0],
            assistObj = res[1],
            subjectObj = {}
        rows.forEach(row => {
          let { account_id, assist_account_json, assist_account_value, } = row,
              arr = (assist_account_json || '').split(','),
              assistAccountNameArr = []
          // row.assist_account_value_arr = (assist_account_value || '').split(',')
          arr.forEach(item => {
            if(assistObj[item]) assistAccountNameArr.push(assistObj[item].assist_account)
          })
          row.assist_account_value_arr = assistAccountNameArr
          subjectObj[account_id] = row
          // if(assistAccountNameArr.length) subjectObj[account_id] = row
        })
        this.setData({
          subjectObj,
        })
        resolve()
      })
    })
  },
  // 获取科目
  getSubjectList() {
    let post = {
      page: 1,
      limit: 0,
      oby: 'account_id',
    }
    // 220531 有下级科目不返回一级科目可选
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Account/query_account_last', post).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        resolve(rows)
      })
    })
  },
  // 获取辅助核算项目
  getAssistProject() {
    return new Promise((resolve, reject) => {
      wx.$post(1, 'AllAssistAccount/select_all_assist_account', {}).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row,
            assistObj = {}
        rows.forEach(row => {
          assistObj[row.row_id] = row
        })
        this.setData({
          assistObj,
        })
        resolve(assistObj)
      })
    })
  },
  getDetlData() {
    let post = {
      row_id: 0,
      voucher_id: this.data.vchrId,
    }
    wx.$post(3, 'Voucher/query_all_voucher', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row,
          row = rows[0],
          { subjectObj, } = this.data,
          obj = {
            voucherId: row.voucher_id,
            date: row.data_date ? wx.$util.formatDate(new Date(row.data_date.replace(/-/g, '/')), 'yyyy-MM-dd') : (row.account_period || ''),
            abstractStr: row.abstract_str,
            list: rows,
            borrow: 0,
            loan: 0,
            inputName: row.input_name,
          }
      rows.forEach(row => {
        let { account_direction, amount, account_id, } = row
        row.textCls = ''
        if(account_direction === '借') {
          row.textCls = 'u-text_green'
          obj.borrow += amount
        } else if(account_direction === '贷') {
          row.textCls = 'u-text_red'
          obj.loan += amount
        }
        if(subjectObj[account_id] && subjectObj[account_id].assist_account_value_arr.length) {
          row.assistAccountLabels = subjectObj[account_id].assist_account_value_arr
          let assistAccountVals = []
          row.assistAccountLabels.forEach((item, i) => {
            let val = row[`quantity_account_${i + 1}_value`]
            if([undefined, null, ].includes(val)) val = ''
            assistAccountVals.push(val)
          })
          row.assistAccountVals = assistAccountVals
        }
      })
      this.setData(obj)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    let { voucher_id, canedit, } = options

    this.setData({
      vchrId: voucher_id,
      edit: Number(canedit),
      urlParams: options,
    })
    await this.ready()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDetlData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
